package item

import (
	"context"
	"strings"
	"time"

	"mall/common/utils/pointy"
	"mall/service/recommended/api/internal/svc"
	"mall/service/recommended/api/internal/types"
	client "mall/service/recommended/common/gorseclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateItemLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdateItemLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateItemLogic {
	return &UpdateItemLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateItemLogic) UpdateItem(req *types.ItemInfo) (resp *types.RowAffectedResp, err error) {
	if len(strings.TrimSpace(req.ItemId)) == 0 {
		return &types.RowAffectedResp{}, nil
	}
	var item = client.ItemPatch{
		IsHidden:   pointy.GetPointer(true),
		Categories: nil,
		Timestamp:  pointy.GetPointer(time.Now()),
		Labels:     nil,
		Comment:    nil,
	}
	if len(strings.TrimSpace(req.IsHidden)) > 0 && req.IsHidden == "0" {
		item.IsHidden = pointy.GetPointer(false)
	}
	if len(strings.TrimSpace(req.Labels)) > 0 {
		item.Labels = strings.Split(req.Labels, ",")
	}
	if len(strings.TrimSpace(req.Category)) > 0 {
		item.Categories = strings.Split(req.Category, ",")
	}
	if len(strings.TrimSpace(req.Comment)) > 0 {
		item.Comment = pointy.GetPointer(req.Comment)
	}
	res, err := l.svcCtx.GorseClient.UpdateItem(l.ctx, req.ItemId, item)
	if err != nil {
		return nil, err
	}

	return &types.RowAffectedResp{
		RowAffected: uint32(res.RowAffected),
	}, nil
}
